package com.sen.uaa.exception;

import com.sen.common.common.response.MessageResult;
import com.sen.common.common.response.ResultMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;

/**
   * @Description 异常
   * @Author esJiang
**/
@Component
@Slf4j
public class BootOauth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    private HttpHeaders getHttpHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        return headers;
    }

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {

        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);

        Exception ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
                causeChain);
        log.error("BootOAuth2WebResponseExceptionTranslator异常:",ase);
        return new ResponseEntity(
                MessageResult.reqFailed(ResultMsgEnum.UNAUTHORIZED), getHttpHeader()
                , HttpStatus.UNAUTHORIZED);
    }


}
